import { View, Text, Image } from '@tarojs/components';
import { useState, useEffect } from 'react';
import { AtButton, AtForm, AtInput } from 'taro-ui';
import creameImg from '@/assets/images/user/creame.png';
import './style.scss';
import { postIDCard, getUserLinealDetail } from '@/service/apis/mine';
import Taro from '@tarojs/taro';

const INPUT_TYPE = {
  NAME: 'name',
  ACCOUNT_NUMBER: 'accountNumber',
};

const verify = /^\d{17}[\d|X]/;

/**
 * 养老卡-实名认证
 */
const AuthCard = () => {
  const querys: any = Taro.getCurrentInstance().router?.params;
  const [formValue, setFormValue] = useState<any>({});
  // 上传身份信息
  const onSubmit = async () => {
    const { name, num, card_img_font_side, card_img_back_side } = formValue;
    if (!verify.test(num)) {
      Taro.showToast({
        title: '请输入正确的身份证号',
        icon: 'none',
      });
      return;
    }
    if (name && num && card_img_font_side && card_img_back_side) {
      try {
        await postIDCard(formValue);
        Taro.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000,
        });
        setTimeout(() => {
          Taro.navigateBack();
        }, 2000);
      } catch (error) {
        Taro.showToast({
          title: '提交失败,请稍后再试～',
          duration: 2000,
        });
      }
    } else {
      Taro.showToast({
        title: '请输入或上传完整信息',
        icon: 'none',
      });
    }
  };

  const handleChange = (type) => {
    return (val) => {
      switch (type) {
        case INPUT_TYPE.NAME:
          setFormValue({
            ...formValue,
            name: val,
          });
          break;
        case INPUT_TYPE.ACCOUNT_NUMBER:
          setFormValue({
            ...formValue,
            num: val,
          });
          break;
      }
    };
  };
  // 上传图片
  const onChangeImage = (type) => {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        const token = Taro.getStorageSync('token');
        Taro.showLoading({
          title: '上传中...',
        });
        Taro.uploadFile({
          url: 'https://wxapi.quyizhan.com.cn/api/up_img',
          filePath: tempFilePaths[0],
          header: {
            'content-type': 'multipart/form-data;',
            Authorization: 'Bearer ' + token,
          },
          name: 'img',
          formData: {
            user: 'test',
          },
          success(res) {
            const data: any = JSON.parse(res.data);
            Taro.hideLoading();
            switch (type) {
              case 'font':
                setFormValue({
                  ...formValue,
                  card_img_font_side: data.img_url,
                });
                break;
              case 'back':
                setFormValue({
                  ...formValue,
                  card_img_back_side: data.img_url,
                });
                break;
            }
          },
        });
      },
    });
  };

  useEffect(() => {
    if (querys.status === '1' || querys.status === '2') {
      getDetail();
    }
  }, []);

  const getDetail = async () => {
    try {
      const data = await getUserLinealDetail();
      console.log(data);
      const { cards } = data;
      const zhengmian = cards.card_img.split(',')[0];
      const fanmian = cards.card_img.split(',')[1];
      setFormValue({
        name: cards.username,
        num: cards.card_number,
        card_img_font_side: zhengmian,
        card_img_back_side: fanmian,
      });
    } catch (err) {
      console.log('error');
    }
  };

  return (
    <AtForm className="auth-card-wrap page-container">
      <View className="input-text-wrap">
        <AtInput
          name="name"
          title="姓名"
          type="text"
          placeholder="请输入"
          value={formValue.name}
          onChange={handleChange(INPUT_TYPE.NAME)}
        />
        <AtInput
          name="num"
          title="身份证号"
          type="text"
          placeholder="请输入"
          value={formValue.num}
          onChange={handleChange(INPUT_TYPE.ACCOUNT_NUMBER)}
        />
      </View>
      <View className="upload-authcard-wrap">
        <Text className="title">上传身份证证件</Text>
        <View className="card-wrap">
          <View className="card-font" onClick={() => onChangeImage('font')}>
            <Image className="back-img" src={creameImg} />
            {formValue.card_img_font_side && (
              <Image className="id-card" src={formValue.card_img_font_side} />
            )}
          </View>
          <Text>身份证正面</Text>
        </View>
        <View className="card-wrap">
          <View className="card-end">
            <Image className="back-img" onClick={() => onChangeImage('back')} src={creameImg} />
            {formValue.card_img_back_side && (
              <Image className="id-card" src={formValue.card_img_back_side} />
            )}
          </View>
          <Text>身份证反面</Text>
        </View>
      </View>
      <AtButton className="submint-btn" onClick={onSubmit}>
        提交
      </AtButton>
    </AtForm>
  );
};
export default AuthCard;
